<script setup>
import { getAllSchedulesService, addScheduleService, updateScheduleService, deleteScheduleService } from '@/api/admin';
import { getAllClinicsService } from '@/api/hospital.js';
import { ref, onMounted, nextTick, watch, computed } from 'vue';
import { ElMessage, ElPagination } from 'element-plus';

const schedules = ref([]); // 存储排班信息
const scheduleDate = ref(''); // 用户选择的日期
const clinicId = ref(null); // 用户选择的科室ID
const clinics = ref([]); // 存储科室信息
const dialogVisible = ref(false); // 控制对话框显示
const addForm = ref({
    doctorId: null,
    scheduleDate: '',
    startTime: '',
    endTime: ''
});
const updateDialogVisible = ref(false); // 控制更新对话框显示
const updateForm = ref({
    scheduleId: null,
    doctorId: null,
    scheduleDate: '',
    startTime: null,
    endTime: null,
    clinicName: null
});

// 新增分页相关状态
const currentPage = ref(1); // 当前页码
const pageSize = ref(10); // 每页显示的条数
const total = ref(0); // 数据总数

// 获取所有排班信息
const fetchSchedules = async (pageNumber = 1) => {
    try {
        console.log('fetchSchedules is called'); // 调试信息
        currentPage.value = pageNumber; // 更新当前页码
        const formattedDate = scheduleDate.value ? formatDate(scheduleDate.value) : null;
        console.log('formattedDate:', formattedDate); // 调试信息
        const response = await getAllSchedulesService(formattedDate, clinicId.value);
        if (response.code === 0) {
            // 对排班数据按照 scheduleDate 进行排序
            response.data.sort((a, b) => new Date(a.scheduleDate) - new Date(b.scheduleDate));
            schedules.value = response.data;
            total.value = schedules.value.length; // 更新数据总数
        } else {
            ElMessage.error(response.message || '获取排班信息失败');
        }
    } catch (error) {
        ElMessage.error('获取排班信息失败');
    }
};

// 分页计算
const currentSchedules = computed(() => {
    return schedules.value.slice(
        (currentPage.value - 1) * pageSize.value,
        currentPage.value * pageSize.value
    );
});

// 格式化日期函数
const formatDate = (date) => {
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份是从0开始的
    const day = String(date.getDate()).padStart(2, '0');
    return `${year}-${month}-${day}`;
};

// 格式化时间函数
const formatTime = (time) => {
    const hours = String(time.getHours()).padStart(2, '0');
    const minutes = String(time.getMinutes()).padStart(2, '0');
    const seconds = String(time.getSeconds()).padStart(2, '0');
    return `${hours}:${minutes}:${seconds}`;
};

// 解析时间函数
const parseTime = (timeString) => {
    if (!timeString) return null;
    const [hours, minutes, seconds] = timeString.split(':');
    const date = new Date();
    date.setHours(parseInt(hours));
    date.setMinutes(parseInt(minutes));
    date.setSeconds(parseInt(seconds));
    return date;
};

// 获取科室信息
const fetchClinics = async () => {
    try {
        console.log('fetchClinics is called'); // 调试信息
        const response = await getAllClinicsService();
        if (response.code === 0) {
            clinics.value = response.data;
            console.log(clinics.value);
        } else {
            ElMessage.error(response.message || '获取科室信息失败');
        }
    } catch (error) {
        ElMessage.error('获取科室信息失败');
    }
};

// 提交添加排班表单
const submitForm = async () => {
    try {
        console.log('submitForm is called'); // 调试信息
        console.log('addForm.value:', addForm.value); // 调试信息，查看表单数据

        const formattedScheduleDate = formatDate(addForm.value.scheduleDate);
        const formattedStartTime = formatTime(addForm.value.startTime);
        const formattedEndTime = formatTime(addForm.value.endTime);

        const requestBody = {
            doctorId: addForm.value.doctorId,
            scheduleDate: formattedScheduleDate,
            startTime: formattedStartTime,
            endTime: formattedEndTime
        };

        const response = await addScheduleService(requestBody);
        if (response.code === 0) {
            ElMessage.success('添加成功');
            dialogVisible.value = false; // 关闭对话框
            await fetchSchedules(); // 刷新排班数据
        } else {
            ElMessage.error(response.message || '添加失败');
        }
    } catch (error) {
        console.error('提交失败', error);
        ElMessage.error('添加失败');
    }
};

// 打开更新对话框
const openUpdateDialog = (row) => {
    updateForm.value = {
        scheduleId: row.scheduleId,
        doctorId: row.doctorId,
        scheduleDate: new Date(row.scheduleDate), // 转换为 Date 对象
        startTime: parseTime(row.startTime),
        endTime: parseTime(row.endTime),
        clinicName: row.clinicName
    };
    updateDialogVisible.value = true; // 显示更新对话框
};

// 提交更新排班表单
const submitUpdateForm = async () => {
    try {
        console.log('submitUpdateForm is called'); // 调试信息
        const formattedScheduleDate = formatDate(updateForm.value.scheduleDate);
        const formattedStartTime = formatTime(updateForm.value.startTime);
        const formattedEndTime = formatTime(updateForm.value.endTime);

        const selectedClinic = clinics.value.find(clinic => clinic.clinicName === updateForm.value.clinicName);
        const clinicId = selectedClinic ? selectedClinic.clinicId : null;

        const requestBody = {
            scheduleId: updateForm.value.scheduleId,
            doctorId: updateForm.value.doctorId,
            scheduleDate: formattedScheduleDate,
            startTime: formattedStartTime,
            endTime: formattedEndTime,
            clinicId: clinicId, // 使用科室ID
            clinicName: updateForm.value.clinicName
        };

        const response = await updateScheduleService(requestBody);
        console.log('response:', response); // 调试信息，查看完整的响应对象

        if (response.code === 0) {
            ElMessage.success('更新成功');
            updateDialogVisible.value = false; // 关闭更新对话框
            await nextTick(() => {
                fetchSchedules(); // 刷新排班数据
            });
        } else {
            ElMessage.error(response.message || '更新失败');
        }
    } catch (error) {
        console.error('更新失败', error);
        ElMessage.error('更新失败');
    }
};

// 删除排班信息
const deleteSchedule = async (scheduleId) => {
    try {
        const response = await deleteScheduleService(scheduleId);
        if (response.code === 0) {
            ElMessage.success('删除成功');
            await fetchSchedules(); // 刷新排班数据
        } else {
            ElMessage.error(response.message || '删除失败');
        }
    } catch (error) {
        console.error('删除失败', error);
        ElMessage.error('删除失败');
    }
};

const resetForm = async () => {
    scheduleDate.value = ''; // 重置日期
    clinicId.value = null; // 重置科室
    schedules.value = []; // 重置排班数据
    await fetchSchedules(); // 重新获取排班数据
};

// 在组件挂载时获取排班数据和科室信息
onMounted(async () => {
    console.log('Schedule.vue: onMounted is called'); // 调试信息
    try {
        await fetchClinics();
        await fetchSchedules();
    } catch (error) {
        console.error('Schedule.vue: Error during onMounted:', error);
    }
});

watch(scheduleDate, async (newScheduleDate) => {
    schedules.value = []; // 重置排班数据
    if (newScheduleDate) {
        await fetchSchedules();
    }
});
</script>
<template>
    <el-container>
      <el-header>
        <h1>排班信息</h1>
      </el-header>
      <el-main>
        <el-form>
          <el-form-item label="选择日期:">
            <el-date-picker v-model="scheduleDate" type="date" />
            <el-form-item label="选择科室">
            <el-select v-model="clinicId" placeholder="请选择科室" style="width: 300px;">
              <el-option
                v-for="clinic in clinics"
                :key="clinic.clinicId"
                :label="clinic.clinicName"
                :value="clinic.clinicId"
              />
            </el-select>
          </el-form-item>
          <el-button type="primary" @click="resetForm">重置查询信息</el-button>
          </el-form-item>
          
  
          
          <el-button type="primary" @click="fetchSchedules">获取排班</el-button>
          <el-button type="primary" @click="dialogVisible = true">添加排班信息</el-button>
        </el-form>
        
        <el-table :data="currentSchedules" style="width: 100%">
          <el-table-column prop="doctorName" label="医生" />
          <el-table-column prop="scheduleDate" label="日期" />
          <el-table-column prop="dayWeek" label="星期" />
          <el-table-column prop="clinicName" label="科室" />
          <el-table-column label="时间">
            <template #default="scope">
              {{ scope.row.startTime }} - {{ scope.row.endTime }}
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template #default="scope">
              <el-button size="mini" type="primary" @click="openUpdateDialog(scope.row)">更新</el-button>
              <el-button size="mini" type="danger" @click="deleteSchedule(scope.row.scheduleId)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
  
        <!-- 分页组件 -->
        <el-pagination
          v-model:current-page="currentPage"
          :page-size="pageSize"
          :total="total"
          layout="total, prev, pager, next, jumper"
          @current-change="fetchSchedules"
        />
      </el-main>
      <el-dialog v-model="dialogVisible" title="添加排班信息">
        <el-form :model="addForm" label-width="120px">
          <el-form-item label="医生ID:">
            <el-input v-model.number="addForm.doctorId" type="number" placeholder="请输入医生ID" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="排班日期:">
            <el-date-picker v-model="addForm.scheduleDate" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="开始时间:">
            <el-time-picker v-model="addForm.startTime" placeholder="选择开始时间" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="结束时间:">
            <el-time-picker v-model="addForm.endTime" placeholder="选择结束时间" style="width: 100%;" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
      <el-dialog v-model="updateDialogVisible" title="更新排班信息">
        <el-form :model="updateForm" label-width="120px">
          <el-form-item label="医生ID:">
            <el-input v-model.number="updateForm.doctorId" type="number" placeholder="请输入医生ID" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="排班日期:">
            <el-date-picker v-model="updateForm.scheduleDate" type="date" placeholder="选择日期" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="开始时间:">
            <el-time-picker v-model="updateForm.startTime" placeholder="选择开始时间" style="width: 100%;" />
          </el-form-item>
          <el-form-item label="结束时间:">
            <el-time-picker v-model="updateForm.endTime" placeholder="选择结束时间" style="width: 100%;" />
          </el-form-item>
          <!-- <el-form-item label="科室名称:">
            <el-select v-model="updateForm.clinicName" placeholder="请选择科室" style="width: 100%;">
              <el-option
                v-for="clinic in clinics"
                :key="clinic.clinicId"
                :label="clinic.clinicName"
                :value="clinic.clinicName"
              />
            </el-select>
          </el-form-item> -->
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="updateDialogVisible = false">取消</el-button>
            <el-button type="primary" @click="submitUpdateForm">确定</el-button>
          </span>
        </template>
      </el-dialog>
    </el-container>
  </template>
  <style scoped>
  .el-container {
    padding: 16px;
  }
  
  .el-form {
    margin-bottom: 16px;
  }
  </style>